package com.feiyu.gen;

import com.feiyu.util.jdbcUtils;

import java.io.*;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * 本类是在生成代码时因为添加字段重新生成
 * <p>
 * Created by nanshouxiao on 2017/7/31 17:20.
 */
public class ReGen {
    public static final Pattern propertiePattern = Pattern.compile("\\S*?((private)|(public)).*?;");

    public static void main(String[] args) {
        addBean();

    }

    private static void addBean() {
        String srcFilePath = "E:/workspace/home/src/main/java/";
        String tableSchema = "home";
        String tableName = "t_sys_role";
        String tablePrefix = "t_";
        String packageName = "org.home.sys";
        String basePackageName = "org.home.base";
        Map<String, String> tableInfo = jdbcUtils.getTableInfo(tableSchema, tableName);
        List<Map<String, String>> columnList = jdbcUtils.getTableColumnInfo(tableSchema, tableName);
        Map<String, Object> dataModel = null;

        String beanClassName = (String) dataModel.get("className");
        String beanFilePath = srcFilePath + packageName.replace(".", "/") + "/bean/" + beanClassName + ".java";
        List<String> fieldList = getExistFieldList(beanFilePath);
        List<Map<String, String>> columnList1 = (List<Map<String, String>>) dataModel.get("columnList");
        List<Map<String, String>> newColumnList = columnList1.stream().filter(col -> {
            String fieldName = String.valueOf(col.get("javaName"));
            return !fieldList.contains(fieldName);
        }).collect(Collectors.toList());
        System.out.println(newColumnList);
        createNewBean(fieldList.get(fieldList.size() - 1), newColumnList, beanFilePath);
    }

    private static List<String> getExistFieldList(String filePath) {
        File file = new File(filePath);
        BufferedReader fileStream = null;
        try {
            fileStream = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
            String read;
            List<String> existsColumnName = new ArrayList<>();
            while ((read = fileStream.readLine()) != null) {
                if (propertiePattern.matcher(read).find()) {
                    String[] strs = read.split("\\s|;|(=.*?;)");
                    existsColumnName.add(strs[strs.length - 1]);
                }
            }
            return existsColumnName;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                fileStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    private static void createNewBean(String lastFieldName, List<Map<String, String>> newField, String filePath) {
        File file = new File(filePath);
        BufferedReader fileStream = null;
        try {
            Map<String, String> temp = generateString(newField);
            fileStream = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
            String read;
            StringBuilder existsColumnName = new StringBuilder();
            while ((read = fileStream.readLine()) != null) {
                if (read.trim().startsWith("@Override")) {
                    existsColumnName.append(temp.get("method")).append("\n\r");
                }
                existsColumnName.append(read).append("\n\r");
                if (read.trim().startsWith("private") && read.trim().endsWith(lastFieldName + ";")) {
                    existsColumnName.append(temp.get("field"));
                }
            }
            System.out.println(existsColumnName);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                fileStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private static Map<String, String> generateString(List<Map<String, String>> newField) {
        StringBuilder field = new StringBuilder();
        StringBuilder method = new StringBuilder();
        newField.forEach(column -> {
            Map<String, String> temp = generateString(column);
            field.append(temp.get("field"));
            method.append(temp.get("getMethod"));
            method.append("\n\r");
            method.append(temp.get("setMethod"));
        });
        Map<String, String> resultMap = new HashMap<>();
        resultMap.put("field", field.toString());
        resultMap.put("method", method.toString());
        return resultMap;
    }

    private static Map<String, String> generateString(Map<String, String> column) {
        String javaName = column.get("javaName");
        String javaName2 = javaName.substring(0, 1).toUpperCase() + javaName.substring(1);
        String javaType = column.get("javaType");
        String columnComment = column.get("columnComment");
        String fieldStr = "    /**\n\r     * " + columnComment + "\n\r     */\n\r    private " + javaType + " " + javaName + ";\n\r";
        String getStr = "     /**\n\r     * 获取 " + columnComment + "\n\r     */\n\r    public get" + javaName2 + "(" + javaType + " " + javaName + "){\n\r        return this."
                + javaName + ";\n\r    }\n\r";
        String setStr = "    /**\n\r     * 设置 " + columnComment + "\n\r     */\n\r    public set" + javaName2 + "(" + javaType + " " + javaName + "){\n\r        this."
                + javaName + "=" + javaName + ";\n\r    }\n\r";
        Map<String, String> resultMap = new HashMap<>();
        resultMap.put("field", fieldStr);
        resultMap.put("getMethod", getStr);
        resultMap.put("setMethod", setStr);
        return resultMap;
    }
}
